package cn.git.shiro.controller;

import cn.git.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 登录controller
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-26
 */
@RestController
@RequestMapping("/shiro")
public class LoginController {

    /**
     * 登录
     *
     * @param username
     * @param password
     * @param rememberMe
     * @return
     */
    @GetMapping("/login")
    public String login(@RequestParam(value = "username") String username,
                        @RequestParam(value = "password") String password,
                        @RequestParam(value = "rememberMe", defaultValue = "false") boolean rememberMe) {
        // 1.获取登录信息
        Subject subject = SecurityUtils.getSubject();
        // 2.封装token登录信息
        AuthenticationToken token = new UsernamePasswordToken(username, password, rememberMe);
        // 3.登录
        try {
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
            return "loginFail";
        }
        return "loginSuccess";
    }

    /**
     * 登录成功,rememberMe测试
     *
     * @return
     */
    @GetMapping("/login/remember")
    public String rememberLogin() {
        // 获取登录查询用户基本信息
        Subject subject = SecurityUtils.getSubject();
        // 登录成功后，可以从Subject中获取已绑定的用户信息
        PrincipalCollection principals = subject.getPrincipals();
        if (!principals.isEmpty()) {
            User currentUser = (User) principals.getPrimaryPrincipal(); // 假设User是Principal类型
            // 现在你可以使用currentUser对象，这是你在Realm中查询并验证过的用户信息
            System.out.println(currentUser.toString());
        }

        return "rememberLogin";
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "logout";
    }

    /**
     * 角色测试
     *
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping("/role")
    public String role() {
        return "admin";
    }

    /**
     * 权限验证
     *
     * @return
     */
    @RequiresPermissions("user:add")
    @GetMapping("/permissions")
    public String permissions() {
        return "permissions";
    }
}
